package org.jeecg.modules.music.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.music.entity.MusArtist;
import org.jeecg.modules.music.entity.MusSong;
import org.jeecg.modules.music.service.IMusArtistService;
import org.jeecg.modules.music.service.IMusSongArtistService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j
@Api(tags="歌手管理")
@RestController
@RequestMapping("/mus/artist")
public class MusArtistController {

    @Autowired
    private IMusArtistService musArtistService;

    @Autowired
    private IMusSongArtistService musSongArtistService;

    @Resource
    private BaseCommonService baseCommonService;

    @Value("${jeecg.path.upload}")
    private String upLoadPath;


    @ApiOperation("添加")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result<MusArtist> add(@RequestBody JSONObject jsonObject){
        Result<MusArtist> result = new Result<MusArtist>();

        try{
            MusArtist artist = JSON.parseObject(jsonObject.toJSONString(),MusArtist.class);
            artist.setCreateTime(new Date());
            artist.setStatus(1);
            artist.setDelFlag(CommonConstant.DEL_FLAG_0);
            musArtistService.saveArtist(artist);
            result.success("添加成功！");
        }catch (Exception e){
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    @ApiOperation("编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
    public Result<MusArtist> edit(@RequestBody JSONObject jsonObject) {
        Result<MusArtist> result = new Result<MusArtist>();
        try {
            MusArtist artist = musArtistService.getById(jsonObject.getString("id"));
            baseCommonService.addLog("编辑用户，id： " +jsonObject.getString("id") ,CommonConstant.LOG_TYPE_2, 2);
            if(artist==null) {
                result.error500("未找到对应实体");
            }else {
                MusArtist musArtist = JSON.parseObject(jsonObject.toJSONString(), MusArtist.class);
                artist.setUpdateTime(new Date());
                musArtistService.editArtist(musArtist);
                result.success("修改成功!");
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    @ApiOperation("删除")
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        baseCommonService.addLog("删除歌手，id： " +id ,CommonConstant.LOG_TYPE_2, 3);
        this.musArtistService.deleteArtist(id);
        return Result.ok("删除成功");
    }

    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        baseCommonService.addLog("批量删除， ids： " +ids ,CommonConstant.LOG_TYPE_2, 3);
        this.musArtistService.deleteBatchArtists(ids);
        return Result.ok("批量删除用户成功");
    }

    @ApiOperation("列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<IPage<MusArtist>> queryPageList(MusArtist artist, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<MusArtist>> result = new Result<IPage<MusArtist>>();
        QueryWrapper<MusArtist> queryWrapper = QueryGenerator.initQueryWrapper(artist, req.getParameterMap());
        //用户ID
        String code = req.getParameter("code");
        if(oConvertUtils.isNotEmpty(code)){
            queryWrapper.in("id",Arrays.asList(code.split(",")));
            pageSize = code.split(",").length;
        }
        String status = req.getParameter("status");
        if(oConvertUtils.isNotEmpty(status)){
            queryWrapper.eq("status", Integer.parseInt(status));
        }
        queryWrapper.orderByDesc(true,"initial");
        Page<MusArtist> page = new Page<MusArtist>(pageNo, pageSize);
        IPage<MusArtist> pageList = musArtistService.page(page,queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 冻结&解冻
     * @param jsonObject
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/frozenBatch", method = RequestMethod.PUT)
    public Result<SysUser> frozenBatch(@RequestBody JSONObject jsonObject) {
        Result<SysUser> result = new Result<SysUser>();
        try {
            String ids = jsonObject.getString("ids");
            String status = jsonObject.getString("status");
            String[] arr = ids.split(",");
            for (String id : arr) {
                if(oConvertUtils.isNotEmpty(id)) {
                    this.musArtistService.update(new MusArtist().setStatus(Integer.parseInt(status)),
                            new UpdateWrapper<MusArtist>().lambda().eq(MusArtist::getId,id));
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败"+e.getMessage());
        }
        result.success("操作成功!");
        return result;

    }

    @ApiOperation("详情")
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result<MusArtist> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<MusArtist> result = new Result<MusArtist>();
        MusArtist artist = musArtistService.getById(id);
        if (artist == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(artist);
            result.setSuccess(true);
        }
        return result;
    }


    /**
     * 导出excel
     *
     * @param request
     * @param artist
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(MusArtist artist, HttpServletRequest request) {
        // Step.1 组装查询条件
        QueryWrapper<MusArtist> queryWrapper = QueryGenerator.initQueryWrapper(artist, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //update-begin--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据--------------------
        String selections = request.getParameter("selections");
        if(!oConvertUtils.isEmpty(selections)){
            queryWrapper.in("id",selections.split(","));
        }
        //update-end--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据----------------------
        List<MusArtist> pageList = musArtistService.list(queryWrapper);

        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "歌手列表");
        mv.addObject(NormalExcelConstants.CLASS, MusArtist.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ExportParams exportParams = new ExportParams("歌手列表数据", "导出人:"+user.getRealname(), "导出信息");
        exportParams.setImageBasePath(upLoadPath);
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    @ApiOperation("详情")
    @GetMapping("/detailSongs")
    public Result<IPage<MusSong>> queryPageSongs(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                 @RequestParam(name = "artistId",required = false) String artistId,
                                                 MusSong songParams){
        Result<IPage<MusSong>> result = new Result<IPage<MusSong>>();
        Page<MusSong> page = new Page<MusSong>(pageNo, pageSize);
        IPage<MusSong> pageList = musArtistService.querySongDetailPage(page,artistId,songParams);
        result.setSuccess(true);
        result.setResult(pageList);
        log.info(pageList.toString());
        return result;
    }
}
